package bm.com.ai.server.service;

import bm.com.ai.server.LLModel.constant.ModalityType;
import bm.com.ai.server.dto.MediaContent;
import bm.com.ai.server.dto.MessageRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class MultimodalService {

    public String process(MessageRequest request) {
        // 检测模态类型
        ModalityType modalityType = detectModality(request);
        log.debug("Detected modality type: {} for request {}", modalityType, request.getRequestId());

        // 根据模态类型处理内容
        return switch (modalityType) {
            case TEXT -> processText(request);
            case IMAGE -> processImage(request);
            case AUDIO -> processAudio(request);
            case VIDEO -> processVideo(request);
            case MIXED -> processMixed(request);
        };
    }

    /**
     * 检测请求的模态类型
     */
    public ModalityType detectModality(MessageRequest request) {
        if (request.getMediaContents() == null || request.getMediaContents().isEmpty()) {
            return ModalityType.TEXT;
        }

        List<ModalityType> types = new ArrayList<>();
        for (MediaContent media : request.getMediaContents()) {
            if (media.getType() != null && !types.contains(media.getType())) {
                types.add(media.getType());
            }
        }

        if (types.size() > 1) {
            return ModalityType.MIXED;
        } else if (!types.isEmpty()) {
            return types.get(0);
        } else {
            return ModalityType.TEXT;
        }
    }

    /**
     * 处理文本模态
     */
    private String processText(MessageRequest request) {
        return request.getContent() != null ? request.getContent() : "";
    }

    /**
     * 处理图像模态
     */
    private String processImage(MessageRequest request) {
        // 构建包含图像引用和文本的提示
        StringBuilder prompt = new StringBuilder();

        if (request.getContent() != null && !request.getContent().isEmpty()) {
            prompt.append(request.getContent()).append("\n\n");
        }

        prompt.append("图像内容分析：\n");
        for (MediaContent media : request.getMediaContents()) {
            if (media.getType() == ModalityType.IMAGE) {
                prompt.append("- 图像 ").append(media.getId()).append(": ");
                if (media.getUrl() != null) {
                    prompt.append("URL: ").append(media.getUrl());
                } else if (media.getBase64Data() != null) {
                    prompt.append("Base64数据（已省略）");
                }
                prompt.append("\n");
            }
        }

        return prompt.toString();
    }

    /**
     * 处理音频模态
     */
    private String processAudio(MessageRequest request) {
        // 实际应用中应先将音频转换为文本
        StringBuilder prompt = new StringBuilder();

        if (request.getContent() != null && !request.getContent().isEmpty()) {
            prompt.append(request.getContent()).append("\n\n");
        }

        prompt.append("音频内容分析：\n");
        for (MediaContent media : request.getMediaContents()) {
            if (media.getType() == ModalityType.AUDIO) {
                prompt.append("- 音频 ").append(media.getId()).append(": ");
                if (media.getUrl() != null) {
                    prompt.append("URL: ").append(media.getUrl());
                } else if (media.getBase64Data() != null) {
                    prompt.append("Base64数据（已省略）");
                }
                prompt.append("\n");
            }
        }

        prompt.append("\n请分析上述音频内容并回答问题。");
        return prompt.toString();
    }

    /**
     * 处理视频模态
     */
    private String processVideo(MessageRequest request) {
        // 实际应用中应先处理视频，提取关键帧和音频
        StringBuilder prompt = new StringBuilder();

        if (request.getContent() != null && !request.getContent().isEmpty()) {
            prompt.append(request.getContent()).append("\n\n");
        }

        prompt.append("视频内容分析：\n");
        for (MediaContent media : request.getMediaContents()) {
            if (media.getType() == ModalityType.VIDEO) {
                prompt.append("- 视频 ").append(media.getId()).append(": ");
                if (media.getUrl() != null) {
                    prompt.append("URL: ").append(media.getUrl());
                } else if (media.getBase64Data() != null) {
                    prompt.append("Base64数据（已省略）");
                }
                prompt.append("\n");
            }
        }

        prompt.append("\n请分析上述视频内容并回答问题。");
        return prompt.toString();
    }

    /**
     * 处理混合模态
     */
    private String processMixed(MessageRequest request) {
        // 处理混合类型的内容
        StringBuilder prompt = new StringBuilder();

        if (request.getContent() != null && !request.getContent().isEmpty()) {
            prompt.append(request.getContent()).append("\n\n");
        }

        prompt.append("多媒体内容分析：\n");

        // 分类处理不同类型的媒体
        for (ModalityType type : ModalityType.values()) {
            if (type == ModalityType.TEXT || type == ModalityType.MIXED) {
                continue;
            }

            List<MediaContent> mediaOfType = request.getMediaContents().stream()
                    .filter(media -> type.equals(media.getType()))
                    .toList();

            if (!mediaOfType.isEmpty()) {
                prompt.append(type.getDescription()).append("：\n");
                for (MediaContent media : mediaOfType) {
                    prompt.append("- ").append(type.getDescription()).append(" ").append(media.getId()).append(": ");
                    if (media.getUrl() != null) {
                        prompt.append("URL: ").append(media.getUrl());
                    } else if (media.getBase64Data() != null) {
                        prompt.append(type.getDescription()).append("数据（已省略）");
                    }
                    prompt.append("\n");
                }
            }
        }

        prompt.append("\n请综合分析上述所有内容并回答问题。");
        return prompt.toString();
    }

}
